package com.example.tingshu.dao;

import com.example.tingshu.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@Repository
public class UserDao {
    private final DataSource dataSource;

    @Autowired
    public UserDao(DataSource dataSource){
        this.dataSource = dataSource;
    }

    public User selectOneByUsernameAndPassword(String username,String password){
        String sql = "SELECT uid,nickname FROM user WHERE username = ? AND password = ?";
        try (Connection c = dataSource.getConnection()){
            try (PreparedStatement s = c.prepareStatement(sql)){
                s.setString(1,username);
                s.setString(2,password);
                try (ResultSet rs = s.executeQuery()){
                    if (!rs.next()){
                        return null;
                    }

                    User user = new User();
                    user.uid = rs.getInt("uid");
                    user.nickname = rs.getString("nickname");
                    user.username = username;
                    return user;
                }
            }
        }catch (SQLException exc){
            throw new RuntimeException(exc);
        }
    }
}
